package ffr;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import vo.User;

/**
 * Servlet implementation class KongZhi
 */
@WebServlet("/kongzhi")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String name = request.getParameter("xm");
		String pw = request.getParameter("mm");
		String checkcode = request.getParameter("yzm");
		HttpSession session = request.getSession();
		String servercheckcode = (String)session.getAttribute("checkCode");
		User uu = new User(name, pw, null);
		RequestDispatcher dis = null;
		try {
			if(name.equals("")||pw.equals("")||servercheckcode.equals("")) {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("<script>alert('请输入完整信息！');history.back();</script>");
			}
			else if(!servercheckcode.equalsIgnoreCase(checkcode)) {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("<script>alert('验证码错误！');history.back();</script>");
			}
			else if (uu.yanzheng_user(uu.getXm(), uu.getMm())) {
				request.setAttribute("name",name);
				request.setAttribute("password", pw);
				request.getRequestDispatcher("serface.jsp").forward(request, response);
				
			} else {
				response.setContentType("text/html; charset=UTF-8");
				response.getWriter().write("<script>alert('用户名或密码错误！');history.back();</script>");
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();	
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
